package com.example.androidxdemo.fragment

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.ToastUtils
import com.example.androidxdemo.databinding.FragmentBLEBinding
import com.example.androidxdemo.service.TemCollectService
import com.example.androidxdemo.utilities.BLE_REQUEST_CODE

class BLEFragment : BaseFragment(), BluetoothAdapter.LeScanCallback {
    var binding: FragmentBLEBinding? = null

    private val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
        val bluetoothManager = activity?.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothManager.adapter
    }

    private val BluetoothAdapter.isDisabled: Boolean
        get() = !isEnabled


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = FragmentBLEBinding.inflate(inflater, container, false)
        binding.rlFragmentTitle.fragmentTitleDes.text = "蓝牙通讯功能"
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (null != bluetoothAdapter) {
            if (bluetoothAdapter!!.isDisabled) {
                openBt()
            }else {
                scanLeDevice()
            }
        }else {
            findNavController().popBackStack()
            ToastUtils.showShort("蓝牙不可用")
        }
    }

    private fun openBt() {
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivityForResult(enableBtIntent, BLE_REQUEST_CODE)
    }

    private var mScanning: Boolean = false
    private val handler: Handler = Handler()
    private val scanCallback = SampleScanCallback()
    private var mBluetoothLeService: TemCollectService? = null

    // Code to manage Service lifecycle.
    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName, service: IBinder) {
            mBluetoothLeService = (service as TemCollectService.aaa).bb()
            if (!mBluetoothLeService!!.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth")
                findNavController().popBackStack()
            }
            // Automatically connects to the device upon successful start-up initialization.
            mBluetoothLeService!!.connect("aa")
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            mBluetoothLeService = null
        }
    }

    private fun scanLeDevice() {
//        handler.postDelayed({
//            mScanning = false
//            bluetoothAdapter?.bluetoothLeScanner?.stopScan(scanCallback)
//        }, 5000)
//        mScanning = true
//        bluetoothAdapter?.bluetoothLeScanner?.startScan(scanCallback)
        val intent = Intent(requireContext(),TemCollectService ::class.java)
        activity?.bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE)

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            BLE_REQUEST_CODE -> {
                if (resultCode == 0) {
                    ToastUtils.showShort("请打开蓝牙 ")
                    openBt()
                } else if (resultCode == -1) {
                    ToastUtils.showShort("蓝牙被打开 ")
                    scanLeDevice()
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        bluetoothAdapter?.disable()
        binding = null
    }

    override fun onLeScan(device: BluetoothDevice?, rssi: Int, scanRecord: ByteArray?) {
        Log.d(TAG, "获取到设备： ${device?.name}---------设备address： ${device?.address}---------scanRecord: $scanRecord")
    }

    //在mScanCallback的实现里面，得到的ScanResult封装了BluetoothDevice
    class SampleScanCallback : ScanCallback() {
        override fun onBatchScanResults(results: List<ScanResult>) {
            super.onBatchScanResults(results)
            Log.d("zxcv", "a")
        }

        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            Log.d("zxcv", "设备名称： " + result.device.name + "  address:" +result.device.address)
        }

        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            Log.d("zxcv", "d")
        }
    }

}